package com.xie.smfs.item;

import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraft.util.Hand;
import net.minecraft.world.World;
import com.xie.smfs.entity.GhostEntity;
import com.xie.smfs.registry.ModEffects;
import net.minecraft.entity.effect.StatusEffects;
import com.xie.smfs.registry.ModItems;
import java.util.List;
import java.util.UUID;
import net.minecraft.entity.Entity;  // 正确导入
import java.util.Random;
import net.minecraft.particle.ParticleTypes;

public class WhiteGhostCandleItem extends Item {
    // 基础耐久值
    private static final int BASE_DURABILITY = 100;
    // 距离阈值
    private static final double DISTANCE_THRESHOLD = 20.0;

    public WhiteGhostCandleItem(Settings settings) {
        super(settings.maxDamage(BASE_DURABILITY));
    }

    @Override
    public void inventoryTick(ItemStack stack, World world, Entity entity, int slot, boolean selected) {
        super.inventoryTick(stack, world, entity, slot, selected); // 调用父类逻辑
        if (!world.isClient && entity instanceof PlayerEntity player) {
            // 检查玩家是否手持该物品
            if (player.getMainHandStack() == stack || player.getOffHandStack() == stack) {
                attractNearbyGhosts(stack, player);
                // 确定手持的手
                Hand hand = player.getMainHandStack() == stack ? Hand.MAIN_HAND : Hand.OFF_HAND;
                // 每20tick(1秒)消耗1点耐久
                if (world.getTime() % 20 == 0 && !stack.isEmpty()) {
                    stack.damage(1, player, p -> {
                        p.sendToolBreakStatus(hand);
                    });
                }
            }
        }
    }

    private void attractNearbyGhosts(ItemStack stack, PlayerEntity player) {
        World world = player.getWorld();
        // 获取附近的幽灵实体（与红色鬼烛相同范围）
        List<GhostEntity> nearbyGhosts = world.getEntitiesByClass(
            GhostEntity.class,
            player.getBoundingBox().expand(DISTANCE_THRESHOLD),
            ghost -> true
        );

        if (!nearbyGhosts.isEmpty()) {
            // 吸引逻辑实现
            for (GhostEntity ghost : nearbyGhosts) {
                // 设置幽灵目标为手持白鬼烛的玩家
                ghost.setTarget(player);
            }
        }
    }

    // 判断玩家是否手持白色鬼烛
    public static boolean isHoldingWhiteCandle(PlayerEntity player) {
        return player.getMainHandStack().isOf(ModItems.WHITE_GHOST_CANDLE) || 
               player.getOffHandStack().isOf(ModItems.WHITE_GHOST_CANDLE);
    }
}